﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;

namespace Trentacular.SharePoint.Util
{
    public static class EnumUtils
    {
        /// <summary>
        /// Converts the string representation of the name or numeric value of one or
        /// more enumerated constants to an equivalent enumerated object.
        /// </summary>
        /// <typeparam name="TEnum">The Enum type to parse</typeparam>
        /// <param name="value">A string containing the name or value to convert.</param>
        /// <returns>An object of type enumType whose value is represented by value.</returns>
        public static TEnum Parse<TEnum>(string value, bool ignoreCase) where TEnum : struct
        {
            return (TEnum) Enum.Parse(typeof(TEnum), value, ignoreCase);
        }

        public static TEnum Parse<TEnum>(string value) where TEnum : struct
        {
            return Parse<TEnum>(value, true);
        }

        public static string GetDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            var descAttribute = fi.GetFirstCustomAttribute<DescriptionAttribute>(false);
            return (descAttribute != null) ? descAttribute.Description : value.ToString();
        }

        // TODO: Possibly return a generic type
        public static IList GetNameValueList<TEnum>() where TEnum : struct
        {
            ArrayList list = new ArrayList();
            foreach (Enum value in Enum.GetValues(typeof(TEnum)))
            {
                list.Add(new { Name = EnumUtils.GetDescription(value), Value = Convert.ToInt32(value) });
            }
            return list;
        }
    }
}
